<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import Captcha from '@/components/Captcha.vue'
import { login } from '@/api/auth'

const router = useRouter()

const loginForm = ref({
  username: '',
  password: '',
  captcha: ''
})

const captchaRef = ref(null)

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少 6 个字符', trigger: 'blur' }
  ],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const formRef = ref(null)
const loading = ref(false)

const verifyCaptcha = async (captcha) => {
  try {
    const response = await request.post('/api/captcha/verify', { captcha })
    return response
  } catch (error) {
    console.error('验证验证码失败:', error)
    return { success: false, message: '验证码验证失败' }
  }
}

const handleLogin = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true

      try {
        const captchaResult = await verifyCaptcha(loginForm.value.captcha)

        if (!captchaResult.success) {
          ElMessage.error(captchaResult.message || '验证码错误')
          loginForm.value.captcha = ''
          captchaRef.value?.refreshCaptcha()
          loading.value = false
          return
        }

        const result = await login({
          username: loginForm.value.username,
          password: loginForm.value.password
        })

        if (result.success) {
          localStorage.setItem('adminToken', result.data.token)
          localStorage.setItem('adminUser', JSON.stringify(result.data.user))

          ElMessage.success('登录成功！')
          router.push('/dashboard')
        } else {
          ElMessage.error(result.message || '登录失败')
          loginForm.value.captcha = ''
          captchaRef.value?.refreshCaptcha()
        }
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error('登录失败，请检查网络或后端服务')
        loginForm.value.captcha = ''
        captchaRef.value?.refreshCaptcha()
      }

      loading.value = false
    }
  })
}
</script>

<template>
  <div class="login-container">
    <div class="welcome-area">
      <div class="welcome-content">
        <h1 class="welcome-title">Trave 旅行日记</h1>
        <h2 class="welcome-subtitle">后台管理系统</h2>
        <p class="welcome-text">管理您的旅行平台，让每一次旅程都充满意义</p>
        <div class="welcome-features">
          <div class="feature-item">
            <span class="feature-icon">👥</span>
            <span>用户管理</span>
          </div>
          <div class="feature-item">
            <span class="feature-icon">📝</span>
            <span>内容审核</span>
          </div>
          <div class="feature-item">
            <span class="feature-icon">🌆</span>
            <span>城市维护</span>
          </div>
          <div class="feature-item">
            <span class="feature-icon">💬</span>
            <span>社区管理</span>
          </div>
        </div>
      </div>
    </div>

    <div class="login-card">
      <div class="login-header">
        <h1 class="logo">🌏 管理员登录</h1>
      </div>

      <el-form
        ref="formRef"
        :model="loginForm"
        :rules="rules"
        class="login-form"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            clearable
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="captcha">
          <div class="captcha-row">
            <el-input
              v-model="loginForm.captcha"
              placeholder="请输入验证码"
              size="large"
              maxlength="4"
              clearable
            >
              <template #prefix>
                <el-icon><CircleCheck /></el-icon>
              </template>
            </el-input>
            <Captcha ref="captchaRef" :width="120" :height="52" />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            @click="handleLogin"
            class="login-button"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-tips">
        <el-alert
          title="测试账号：admin / admin123"
          type="info"
          :closable="false"
          show-icon
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 100vh;
  position: relative;
  padding: 60px 120px;
  background-image: url('@/assets/login-bg.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-color: #f5f7fa;
  gap: 80px;
}

.welcome-area {
  flex: 1;
  max-width: 600px;
  animation: slideInLeft 0.6s ease-out;
}

@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-50px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.welcome-content {
  color: white;
  text-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
}

.welcome-title {
  font-size: 56px;
  font-weight: 800;
  margin: 0 0 12px 0;
  line-height: 1.2;
  letter-spacing: -1px;
}

.welcome-subtitle {
  font-size: 32px;
  font-weight: 600;
  margin: 0 0 24px 0;
  opacity: 0.95;
}

.welcome-text {
  font-size: 18px;
  line-height: 1.8;
  margin: 0 0 30px 0;
  opacity: 0.9;
  max-width: 480px;
}

.welcome-features {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  max-width: 400px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.feature-item:hover {
  background: rgba(255, 255, 255, 0.25);
  transform: translateY(-2px);
}

.feature-icon {
  font-size: 24px;
}

.login-card {
  width: 100%;
  max-width: 480px;
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  padding: 50px 45px;
  box-shadow: 0 30px 80px rgba(0, 0, 0, 0.3);
  position: relative;
  z-index: 1;
  animation: slideInRight 0.6s ease-out;
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(50px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.login-header {
  text-align: left;
  margin-bottom: 45px;
}

.logo {
  margin: 0 0 12px 0;
  font-size: 36px;
  color: #1a1a1a;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 10px;
  letter-spacing: -0.5px;
}

.login-header h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  color: #333;
  font-weight: 600;
}

.login-form {
  margin-top: 0;
}

.login-form :deep(.el-form-item) {
  margin-bottom: 24px;
}

.login-form :deep(.el-input__wrapper) {
  height: 52px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.login-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.login-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 3px rgba(6, 182, 212, 0.15);
}

.login-form :deep(.el-input__inner) {
  font-size: 15px;
}

.captcha-row {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-row .el-input {
  flex: 1;
}

.login-button {
  width: 100%;
  height: 52px;
  font-size: 16px;
  font-weight: 600;
  margin-top: 20px;
  background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
  border: none;
  border-radius: 12px;
  transition: all 0.3s ease;
  letter-spacing: 0.5px;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 28px rgba(6, 182, 212, 0.4);
}

.login-button:active {
  transform: translateY(0);
}

.login-tips {
  margin-top: 30px;
}

.login-tips :deep(.el-alert) {
  border-radius: 12px;
  background: rgba(207, 250, 254, 0.8);
  border-color: rgba(6, 182, 212, 0.3);
}

@media (max-width: 1280px) {
  .welcome-title {
    font-size: 48px;
  }

  .welcome-subtitle {
    font-size: 28px;
  }
}

@media (max-width: 1024px) {
  .login-container {
    justify-content: center;
    padding: 40px 30px;
    gap: 0;
  }

  .welcome-area {
    display: none;
  }

  .login-card {
    max-width: 440px;
  }
}

@media (max-width: 768px) {
  .login-container {
    padding: 20px;
  }

  .login-card {
    padding: 35px 30px;
  }

  .logo {
    font-size: 28px;
  }
}
</style>
